package com.sea.base.page

import androidx.annotation.IntRange
import com.sea.base.vm.BaseViewModel
import com.sea.base.vm.UiState
import java.io.Serializable

/**
 * 分页功能
 * @param isAuto 是否自动变化（拉的越多，变得越大，最高8倍）
 */
class MyPage(
    @IntRange(from = 1) private val defPageSize: Int = 10,
    private val isAuto: Boolean = true
) : Serializable {

    private var defPageNum = 1

    /**
     * 是否是初始化状态，需手动调整
     */
    var isInit = true

    val isFirstPage get() = defPageNum == 1

    val pageNum: Int
        get() {
            var newPageNum = defPageNum
            if (isAuto) {
                var newPageSize = defPageSize
                while (newPageNum > 8 && newPageSize < defPageSize * 8) {
                    newPageNum -= 4
                    newPageSize *= 2
                }
            }
            return newPageNum
        }

    val pageSize: Int
        get() {
            var newPageSize = defPageSize
            if (isAuto) {
                var newPageNum = defPageNum
                newPageSize = defPageSize
                while (newPageNum > 8 && newPageSize < defPageSize * 8) {
                    newPageNum -= 4
                    newPageSize *= 2
                }
            }
            return newPageSize
        }

    /**
     * 重置为1
     */
    fun reset(): MyPage {
        defPageNum = 1
        return this
    }

    /**
     * 重置为1，并且状态改为init
     */
    fun reInit(): MyPage {
        isInit = true
        return reset()
    }

    fun nextPage(): MyPage {
        defPageNum++
        isInit = false
        return this
    }

    /**
     * 回退
     */
    fun previousPage() {
        if (defPageNum > 1) {
            defPageNum--
        }
    }

    /**
     * 方便统一方法时当参数调用
     */
    fun changeState(state: MyPageState?): MyPage {
        when (state) {
            MyPageState.STATE_RESET -> reset()
            MyPageState.STATE_RE_INIT -> reInit()
            MyPageState.STATE_NEXT_PAGE -> nextPage()
            MyPageState.STATE_PREVIOUS_PAGE -> previousPage()
            null -> {}
        }
        return this
    }

    /**
     * 返回ui状态，供[BaseViewModel.launchLiveData]、[BaseViewModel.createLiveDataLoadingFun]使用
     */
    fun toUiState() = when {
        isInit -> UiState.INIT
        isFirstPage -> UiState.REFRESH
        else -> UiState.MORE
    }

    fun toPageReq() = PageReq(this)
}